C# .NET – Compare Two Different Files line-by-line

C NET Compare Two Different Files line by line

Today in this article, we will learn a simple and easy approach In C# .NET – Compare Two Different Files line-by-line. You might find need to compare two files line by line.

The file can be compared in a variety of methods to identify differences or common lines.

This piece walks readers through the process of comparing two files to determine whether their contents differ and how to create a file of differences if they do.

This comparison examines the contents of the two files line by line, checking each line for any order that may or may not correspond to other files’ names, locations, times, or other characteristics.

Multiple modules can be used in C# to identify variations or commonalities.

File A – We have the below file with the content.

Compare two Files line by line in Python 2

File B – We have the below file with the content different from the previous file as highlighted.

Compare two different files line by line in python 2

Approach 1 – File Line compare using Linq Contains method

Using LInq Contains method determines whether a sequence contains a specified element by using the default equality comparer.

var listA = File.ReadAllLines("DataA");
 
var listExceptAB = File.ReadAllLines("DataB")
.Where(line =>!listA.Contains(line));

Approach 2 – File Line compare using Linq Except method

var listA = File.ReadAllLines("DataA");
 
var listExceptAB = File.ReadAllLines("DataB")
.Except(listA );

We can use a linq Except for method which helps produce a set difference of two file line by line by using the default equality comparer to compare values.

Except works fine on any IEnumerable properties as explained below

Output

Once the code is executed, you shall see the file is generated with only delta changes having the differences i.e return all the elements which exist in File A but don’t in File B.

27 APOSTROPHE A7 SECTION SIGN
23 NUMBER SIGN A3 POUND SIGN

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *